import hashlib
import json

from django.core import serializers
from django.utils.datastructures import MultiValueDictKeyError

from rest_framework.response import Response
from rest_framework.views import APIView

from hospital_model.models import ProjectModel
from reservation_model.models import ReservationOrderModel
from user_model.models import UserModel, RelationModel, AssociatedModel, ComplainModel, RelevanceModel
from user_model.serializer import RegisterSerializer, LoginSerializer, ModificationSerializer, ComplaintSerializer
from django.core.cache import cache
from utils.check import is_valid_idcard, is_phone, is_code
from utils.sms import sms_code
# from utils.user_jwt import create_token
from utils.jwt_auth import create_token
from extensions.auth import JwtQueryParamAuthentication


# 注册验证码获取
class GetRegisterView(APIView):
    # authentication_classes = []

    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        if is_phone(phone):
            # 验证手机号是否存在
            user = UserModel.objects.filter(u_phone=phone).all()
            if user.count() == 0:
                # code = verification_code()
                # cache.set(phone, code, 60 * 5)
                sms_code(phone)
                data = {
                    'msg': "获取成功",
                    'code': 2000,
                    # 'codes': code
                }
                return Response(data)
            else:
                data = {
                    'msg': "请求频繁，请稍后再操作",
                    'code': 4000,
                }
                return Response(data)
        else:
            data = {
                'msg': "手机号格式不对",
                'code': 4000,
            }
            return Response(data)


# 注册
class RegisterView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            name = request.POST['name']
            password = request.POST['password']
            ID_card = request.POST['ID_card']
            address = request.POST['address']
            phone = request.POST['phone']
            code = request.POST['code']
            emergency_contact = request.POST['emergency_contact']
            print(is_phone(phone), is_code(code), is_valid_idcard(ID_card))
            if is_phone(phone) and is_code(code) and is_valid_idcard(ID_card):
                users = UserModel.objects.filter(u_IDcard=ID_card).all()
                redis_code = cache.get(phone)
                print(users.count() == 0, redis_code == int(code))
                if users.count() == 0 and redis_code == int(code):
                    UserModel.objects.create(u_name=name, u_password=password, u_IDcard=ID_card, u_address=address,
                                             u_phone=phone, emergency_contact=emergency_contact)
                    cache.delete(phone)
                    token = create_token({'phone':phone})
                    data = {
                        'msg': "用户注册成功",
                        'code': 2000,
                        'token': token
                    }
                    return Response(data)

                else:
                    data = {
                        'msg': "用户注册失败",
                        'code': 4001
                    }
                    return Response(data)

            else:
                data = {
                    'msg': "验证不通过",
                    'code': 4000
                }
                return Response(data)
        else:
            data = {
                'msg': "用户注册失败",
                'code': 4000
            }
            return Response(data)


# 登录
class LoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        # 用户名 和密码  用户名可以是手机号 也可以是身份证号
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            login_name = request.POST['login_name']
            password = request.POST['password']
            user_Id = UserModel.objects.filter(u_IDcard=login_name).all()
            users = UserModel.objects.filter(u_phone=login_name).all()
            if len(login_name) == 18 and user_Id.count() != 0:
                data_lists = (json.loads(serializers.serialize('json', user_Id)))[0]['fields']
                u_password = data_lists['u_password']
                sha_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
                if sha_password == u_password:
                    details = \
                        json.loads(serializers.serialize('json', UserModel.objects.filter(u_IDcard=login_name)))[0][
                            'fields']
                    token = create_token({'username': login_name})
                    data = {
                        'msg': "登录成功",
                        'code': 2000,
                        'data': details,
                        'token': token
                    }
                    return Response(data)
                else:
                    data = {
                        'msg': "登录失败",
                        'code': 4000
                    }
                    return Response(data)
            elif len(login_name) == 11 and users.count() != 0:
                data_lists = (json.loads(serializers.serialize('json', users)))[0]['fields']
                u_password = data_lists['u_password']
                sha_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
                # print(sha_password, u_password)
                if sha_password == u_password:
                    details = \
                        json.loads(serializers.serialize('json', UserModel.objects.filter(u_phone=login_name)))[0][
                            'fields']
                    token = create_token({'username': login_name})
                    data = {
                        'msg': "登录成功",
                        'code': 2000,
                        'data': details,
                        'token': token
                    }
                    return Response(data)
                else:
                    data = {
                        'msg': "登录失败",
                        'code': 4000
                    }
                    return Response(data)
            else:
                data = {
                    'msg': "登录账户有误",
                    'code': 4000
                }
                return Response(data)
        else:
            data = {
                'msg': "用户注册失败",
                'code': 4000
            }
            return Response(data)


# 登录获取验证码
class GetCodeView(APIView):
    # authentication_classes = []

    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        if is_phone(phone):
            # 验证手机号是否存在
            user = UserModel.objects.filter(u_phone=phone).all()
            if user.count() == 0:
                data = {
                    'msg': "没有此用户，去注册吧",
                    'code': 4000
                }
                return Response(data)
            else:
                a_list = cache.get(phone)

                if a_list is None:
                    # code = verification_code()
                    # cache.set(phone, code, 60 * 5)
                    sms_code(phone)
                    data = {
                        'msg': "获取成功",
                        'code': 2000,
                        # 'codes': code
                    }
                    return Response(data)
                else:

                    data = {
                        'msg': "请求频繁，请稍后再操作",
                        'code': 4000,
                    }
                    return Response(data)
        else:
            data = {
                'msg': "手机号格式不对",
                'code': 4000,
            }
            return Response(data)


# 使用短信登录
class CodeLoginView(APIView):
    # authentication_classes = []

    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        code = request.POST['code']
        if is_phone(phone) and is_code(code):
            redis_code = cache.get(phone)
            if redis_code == int(code):
                details = \
                    json.loads(serializers.serialize('json', UserModel.objects.filter(u_phone=phone)))[0][
                        'fields']
                cache.delete(phone)
                token = create_token({'username': phone})
                data = {
                    'msg': "登录成功",
                    'code': 2000,
                    'data': details,
                    'token': token
                }
                return Response(data)
            else:
                data = {
                    'msg': "登录失败",
                    'code': 4000,

                }
                return Response(data)
        else:
            data = {
                'msg': "请检查手机号和验证码是否输入正确",
                'code': 2000,

            }
            return Response(data)

    # 使用jwt进行用户认证


# 信息修改
class ModificationView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = ModificationSerializer(data=request.data)
        if serializer.is_valid():
            address = request.POST['address']
            ID_card = request.POST['ID_card']
            users = UserModel.objects.filter(u_IDcard=ID_card).all()
            if users.count() != 0:
                UserModel.objects.filter(u_IDcard=ID_card).update(u_address=address)
                data = {
                    'msg': "用户地址修改成功",
                    'code': 2000
                }
                return Response(data)
            else:
                data = {
                    'msg': "用户地址修改失败",
                    'code': 4000
                }
                return Response(data)
        else:
            data = {
                'msg': "验证不通过",
                'code': 4000
            }
            return Response(data)


# 用户注销
class UnsubscribeView(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        users = UserModel.objects.filter(u_IDcard=ID_card).all()
        if users.count() != 0:
            UserModel.objects.filter(u_IDcard=ID_card).update(u_status='1')
            data = {
                'msg': "用户删除成功",
                'code': 2000
            }
            return Response(data)
        else:
            data = {
                'msg': "用户删除失败",
                'code': 4000
            }
            return Response(data)


# 关联用户
class AssociatedUserView(APIView):
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        # 关联用户姓名
        new_name = request.POST['new_name']
        # 关联用户身份证号
        new_ID_card = request.POST['new_ID_card']
        # 关联用户地址
        new_address = request.POST['new_address']
        # 关联用户关系
        new_relation = request.POST['new_relation']
        users = UserModel.objects.filter(u_IDcard=ID_card).all()
        if users.count() != 0:
            associated = AssociatedModel.objects.filter(user_id=ID_card).all()
            if associated.count() == 0:
                AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                RelationModel.objects.create(r_name=new_name, r_ID_card=new_ID_card, r_address=new_address)
                data = {
                    'msg': "用户添加成功",
                    'code': 2000
                }
                return Response(data)
            else:
                data_lists = (json.loads(serializers.serialize('json', associated)))
                id_card = []
                for data in data_lists:
                    id_card.append(data['fields']['associated_id'])
                if (new_ID_card in id_card):
                    data = {
                        'msg': "用户关系已存在",
                        'code': 4000
                    }
                    return Response(data)
                else:
                    AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                    data = {
                        'msg': "用户关系添加成功",
                        'code': 2000
                    }
                    return Response(data)
        else:
            associated = AssociatedModel.objects.filter(user_id=ID_card).all()
            if associated.count() == 0:
                AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                RelationModel.objects.create(r_name=new_name, r_ID_card=new_ID_card, r_address=new_address)
                data = {
                    'msg': "用户添加成功",
                    'code': 2000
                }
                return Response(data)
            else:
                data_lists = (json.loads(serializers.serialize('json', associated)))
                id_card = []
                for data in data_lists:
                    id_card.append(data['fields']['associated_id'])
                if (new_ID_card in id_card):
                    data = {
                        'msg': "用户关系已存在",
                        'code': 4000
                    }
                    return Response(data)
                else:
                    AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                    data = {
                        'msg': "用户关系添加成功",
                        'code': 2000
                    }
                    return Response(data)


# 建立关联用户
class SetRelevance(APIView):
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        # 关联用户姓名
        new_name = request.POST['new_name']
        # 关联用户身份证号
        new_ID_card = request.POST['new_ID_card']
        # 关联用户地址
        new_address = request.POST['new_address']
        # 关联用户关系
        new_relation = request.POST['new_relation']
        # print(is_valid_idcard(ID_card) and is_valid_idcard(new_ID_card))
        if is_valid_idcard(ID_card) and is_valid_idcard(new_ID_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card, associated_id=new_ID_card, r_status=0)
            if len(is_null) == 0:
                RelevanceModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated_name=new_name,
                                              associated=new_relation, r_address=new_address)
                users = json.loads(serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card,
                                                                                               associated_id=new_ID_card)))
                if len(users) == 0:
                    data = {
                        'msg': "用户关系添加失败",
                        'code': 40001
                    }
                    return Response(data)
                else:
                    da = users[0]['fields']
                    data = {
                        'msg': "用户关系关联成功",
                        'code': 20001,
                        'data': da
                    }
                    return Response(data)
            else:
                RelevanceModel.objects.filter(user_id=ID_card, associated_id=new_ID_card, r_status=1).update(
                    associated_name=new_name, associated=new_relation, r_address=new_address, r_status=0)
                users = json.loads(serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card,
                                                                                               associated_id=new_ID_card)))
                if len(users) == 0:
                    data = {
                        'msg': "用户关系添加失败",
                        'code': 40001
                    }
                    return Response(data)
                else:
                    da = users[0]['fields']
                    data = {
                        'msg': "用户关系关联成功",
                        'code': 20001,
                        'data': da
                    }
                    return Response(data)
        else:
            data = {
                'msg': "身份证号验证不通过",
                'code': 40002
            }
            return Response(data)


# 查询用户关系
class QueryRelevance(APIView):
    # authentication_classes = []
    # authentication_classes = [JwtQueryParamAuthentication, ]
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        datas = []
        if is_valid_idcard(ID_card):
            is_null = json.loads(
                serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card, r_status=0)))
            if len(is_null) == 0:
                data = {
                    'msg': "该用户还没有关联用户",
                    'code': 40002
                }
                return Response(data)
            else:
                for a in is_null:
                    datas.append(a['fields'])
                data = {
                    'msg': "获取成功",
                    'code': 20000,
                    'data': datas
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证号验证不通过",
                'code': 40002
            }
            return Response(data)


# 修改用户关系
class AmendRelevance(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        relevance_card = request.POST['relevance_card']
        associated = request.POST['associated']
        if is_valid_idcard(ID_card) and is_valid_idcard(relevance_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card).update(associated=associated)
            if int(is_null) != 0:
                data = {
                    'msg': "修改成功",
                    'code': 20002,
                }
                return Response(data)
            else:
                data = {
                    'msg': "修改失败",
                    'code': 40002,
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证验证不通过",
                'code': 400020,
            }
            return Response(data)


# 解除用户关系
class DelRelevance(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        relevance_card = request.POST['relevance_card']
        if is_valid_idcard(ID_card) and is_valid_idcard(relevance_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card, associated_id=relevance_card).update(r_status=1)
            if int(is_null) != 0:
                data = {
                    'msg': "解除关联成功",
                    'code': 20002,
                }
                return Response(data)
            else:
                data = {
                    'msg': "解除关联失败",
                    'code': 40002,
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证验证不通过",
                'code': 400020,
            }
            return Response(data)


# 投诉建议
class ComplaintView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = ComplaintSerializer(data=request.data)
        if serializer.is_valid():
            complain = request.POST['complain']
            ID_card = request.POST['ID_card']
            title = request.POST['title']
            image = request.FILES.get('file')
            # print(request.META)
            print(request.data.get('file'), request.FILES.get('file'))
            # print(image,complain,ID_card,title)
            ComplainModel.objects.create(c_image=image, c_complain=complain, c_title=title, c_IDcard=ID_card)
            data = {
                'msg': "投诉成功",
                'code': 2000
            }
            return Response(data)
        else:
            data = {
                'msg': "投诉失败",
                'code': 4000
            }
            return Response(data)


# 所有投诉建议
class AllComplaintView(APIView):
    def post(self, request, *args, **kwargs):
        data = []
        try:
            status = request.POST['status']
            ID_card = request.POST['ID_card']
            all_complain = ComplainModel.objects.filter(c_IDcard=ID_card, c_status=status).all()
            data_lists = (json.loads(serializers.serialize('json', all_complain)))
            for data_list in data_lists:
                data.append(data_list['fields'])
            data = {
                'msg': "所有投诉1",
                'code': 2000,
                'data': data
            }
            return Response(data)

        except MultiValueDictKeyError:
            ID_card = request.POST['ID_card']
            all_complain = ComplainModel.objects.filter(c_IDcard=ID_card).all()
            data_lists = (json.loads(serializers.serialize('json', all_complain)))
            for data_list in data_lists:
                data.append(data_list['fields'])
            data = {
                'msg': "所有投诉2",
                'code': 2000,
                'data': data
            }
            return Response(data)

        # except:
        #     ID_card = request.POST['ID_card']
        #     all_complain = ComplainModel.objects.filter(c_IDcard=ID_card).all()
        #     data_lists = (json.loads(serializers.serialize('json', all_complain)))
        #     for data_list in data_lists:
        #         data.append(data_list['fields'])
        #     data = {
        #         'msg': "所有投诉2",
        #         'code': 2000,
        #         'data': data
        #     }
        #     return Response(data)


# 删除投诉建议
class DelComplaintView(APIView):
    def post(self, request, *args, **kwargs):
        complaint_id = request.POST['complaint_id']
        if ((ComplainModel.objects.filter(c_id=complaint_id)).count() != 0):
            ComplainModel.objects.filter(c_id=complaint_id).update(c_status='1')
            data = {
                'msg': "删除成功",
                'code': 2000
            }
            return Response(data)
        else:
            data = {
                'msg': "删除失败",
                'code': 4000
            }
            return Response(data)


# 忘记密码获取验证码
class ForgetPasswordCode(APIView):
    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        if is_phone(phone):
            # 验证手机号是否存在
            user = UserModel.objects.filter(u_phone=phone).all()
            if len(user) == 0:
                data = {
                    'msg': "该手机号还没有注册",
                    'code': 4000,
                }
                return Response(data)
            else:
                a_list = cache.get(phone)
                if a_list is None:
                    sms_code(phone)
                    data = {
                        'msg': "获取成功",
                        'code': 2000,
                        # 'codes': code
                    }
                    return Response(data)
                else:

                    data = {
                        'msg': "请求频繁，请稍后再操作",
                        'code': 4000,
                    }
                    return Response(data)

        else:
            data = {
                'msg': "手机号格式不对",
                'code': 4000,
            }
            return Response(data)


# 忘记密码
class ForgetPassword(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        phone = request.POST['phone']
        code = request.POST['code']
        password = request.POST['password']
        if len(UserModel.objects.filter(u_IDcard=id_card, u_phone=phone)) == 0:
            data = {
                'msg': "用户手机号和身份证号不匹配",
                'code': 4000,
            }
            return Response(data)
        else:
            redis_code = cache.get(phone)
            if (redis_code == int(code)) and len(password) > 6:
                UserModel.objects.filter(u_phone=phone).update(
                    u_password=hashlib.sha256(password.encode("utf-8")).hexdigest())
                cache.delete(phone)
                data = {
                    'msg': "密码设置成功",
                    'code': 2000,
                }
                return Response(data)
            else:
                data = {
                    'msg': "验证码错误",
                    'code': 4000,
                }
                return Response(data)


# 获取用户详情
class UserDetails(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        details = json.loads(serializers.serialize('json', UserModel.objects.filter(u_IDcard=id_card)))[0]['fields']
        data = {
            'msg': "获取成功",
            'code': 2000,
            'data': details

        }
        return Response(data)


# 获取用户所有预约信息
class UserAll(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        all_json = ReservationOrderModel.objects.filter(r_IDcard=id_card)
        if len(all_json) == 0:
            data = {
                'msg': "没有预约信息",
                'code': 4000,

            }
            return Response(data)
        else:
            all_li = json.loads(serializers.serialize('json', all_json))
            li = []
            dict = {}
            for a in all_li:
                dict['data'] = a['fields']['r_data']
                dict['time'] = a['fields']['r_time']
                # dict['r_status'] = a['fields']['r_status']
                # dict['r_number'] = a['fields']['r_number']
                for i in json.loads(
                        serializers.serialize('json', ProjectModel.objects.filter(p_id=a['fields']['project_id']))):
                    dict['name'] = i['fields']['p_name']
                li.append(dict)
            data = {
                'msg': "查询成功",
                'code': 2000,
                'data': li

            }
            return Response(data)


# 已预约还没有体检的
class HaveBeenUsed(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        all_json = ReservationOrderModel.objects.filter(r_IDcard=id_card, r_status=0)
        if len(all_json) == 0:
            data = {
                'msg': "没有预约信息",
                'code': 4000,

            }
            return Response(data)
        else:
            all_li = json.loads(serializers.serialize('json', all_json))
            li = []
            dict = {}
            for a in all_li:
                dict['data'] = a['fields']['r_data']
                dict['time'] = a['fields']['r_time']
                # dict['r_status'] = a['fields']['r_status']
                # dict['r_number'] = a['fields']['r_number']
                for i in json.loads(
                        serializers.serialize('json', ProjectModel.objects.filter(p_id=a['fields']['project_id']))):
                    dict['name'] = i['fields']['p_name']
                li.append(dict)
            data = {
                'msg': "查询成功",
                'code': 2000,
                'data': li

            }
            return Response(data)


# 已预约已体检的
class BeenUsed(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        all_json = ReservationOrderModel.objects.filter(r_IDcard=id_card, r_status=1)
        if len(all_json) == 0:
            data = {
                'msg': "没有体检过",
                'code': 4000,

            }
            return Response(data)
        else:
            all_li = json.loads(serializers.serialize('json', all_json))
            li = []
            dict = {}
            for a in all_li:
                dict['data'] = a['fields']['r_data']
                dict['time'] = a['fields']['r_time']
                # dict['r_status'] = a['fields']['r_status']
                # dict['r_number'] = a['fields']['r_number']
                for i in json.loads(
                        serializers.serialize('json', ProjectModel.objects.filter(p_id=a['fields']['project_id']))):
                    dict['name'] = i['fields']['p_name']
                li.append(dict)
            data = {
                'msg': "查询成功",
                'code': 2000,
                'data': li

            }
            return Response(data)


# 预约已取消的
class Cancel(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        all_json = ReservationOrderModel.objects.filter(r_IDcard=id_card, r_number__gt=0)
        if len(all_json) == 0:
            data = {
                'msg': "没有取消过",
                'code': 4000,

            }
            return Response(data)
        else:
            all_li = json.loads(serializers.serialize('json', all_json))
            li = []
            dict = {}
            for a in all_li:
                dict['data'] = a['fields']['r_data']
                dict['time'] = a['fields']['r_time']
                # dict['r_status'] = a['fields']['r_status']
                # dict['r_number'] = a['fields']['r_number']
                for i in json.loads(
                        serializers.serialize('json', ProjectModel.objects.filter(p_id=a['fields']['project_id']))):
                    dict['name'] = i['fields']['p_name']
                li.append(dict)
            data = {
                'msg': "查询成功",
                'code': 2000,
                'data': li

            }
            return Response(data)
